package com.example.demo.util;

import com.example.demo.bean.TableBean;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author hweiyu
 * @Description
 * @Date 2022/6/23 16:55
 */
@SuppressWarnings("unchecked")
public class TableUtil {

    public static void setData(TableView<?> table, List<?> list) {
        ObservableList data = wrapData(list);
        table.setItems(data);
    }

    private static ObservableList<?> wrapData(List<?> list) {
        if (null == list) {
            list = new ArrayList<>(0);
        }
        return FXCollections.observableArrayList(list);
    }

    public static void initPage(Pagination page, Callback<Integer, Node> pageFactory) {
        page.setPageCount(1);
        page.setCurrentPageIndex(0);
        page.setMaxPageIndicatorCount(5);
        page.setPageFactory(pageFactory);
    }

    public static void initTable(TableView table) {
        for (Object column : table.getColumns()) {
            TableColumn col = (TableColumn) column;
            if (col.getId().equals("checked")) {
                col.setCellFactory(param -> new CheckedCell());
            }
            col.setCellValueFactory(new PropertyValueFactory(col.getId()));
        }
    }

    public static class CheckedCell extends TableCell {
        private CheckBox checkBox;
        public CheckedCell() {
            checkBox = new CheckBox();
            checkBox.setDisable(false);
            checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
                TableBean row = (TableBean) (getTableRow().getItem());
                if (null != row && null != newValue) {
                    row.setChecked(newValue);
                }
            });
            this.setGraphic(checkBox);
            this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            this.setAlignment(Pos.CENTER);
            this.setEditable(true);
        }

        @Override
        public void updateItem(Object item, boolean empty) {
            super.updateItem(item, empty);
            //判断是否要显示checkbox，比如在最后一页中，数据长度不等于pageSize时，剩余行数里的checkbox不用显示
            this.setGraphic(empty ? null : checkBox);
        }
    }

}
